<template>
  <view class="container">
    <view class="title">AI图像生成</view>
    
    <view class="section">
      <view class="section-title">提示词设置</view>
      <view class="form">
        <textarea v-model="prompt" placeholder="请输入正向提示词，如：一只可爱的猫咪" class="prompt-input" />
        <textarea v-model="negativePrompt" placeholder="请输入负向提示词，如：低质量, 模糊" class="prompt-input" />
      </view>
      <button type="primary" @click="handleGenerateImage">生成图像</button>
    </view>
    
    <view class="section" v-if="isLoading">
      <view class="loading">
        <text>正在生成中，请稍候...</text>
      </view>
    </view>
    
    <view class="section" v-if="generatedImages.length > 0">
      <view class="section-title">生成结果</view>
      <scroll-view scroll-y class="image-list">
        <view 
          class="image-item" 
          v-for="(image, index) in generatedImages" 
          :key="index"
          @click="previewImage(image.fileUrl)"
        >
          <image :src="image.fileUrl" mode="aspectFill" class="result-image" />
          <view class="image-info">
            <text class="image-index">图片 {{index + 1}}</text>
            <button size="mini" type="default" @click.stop="saveImage(image.fileUrl)">保存</button>
          </view>
        </view>
      </scroll-view>
    </view>
    
    <view class="section">
      <view class="section-title">历史记录</view>
      <scroll-view scroll-y class="history-list" v-if="historyList.length > 0">
        <view class="history-item" v-for="(item, index) in historyList" :key="index">
          <view class="history-prompt">{{item.prompt}}</view>
          <view class="history-images">
            <image 
              v-for="(img, imgIndex) in item.images" 
              :key="imgIndex" 
              :src="img.fileUrl" 
              mode="aspectFill" 
              class="history-image"
              @click="previewImage(img.fileUrl)"
            />
          </view>
          <view class="history-time">{{item.time}}</view>
        </view>
      </scroll-view>
      <view class="empty" v-else>暂无历史记录</view>
    </view>
  </view>
</template>

<script>
import runningHubUtils from '@/utils/runningHubUtils';

export default {
  data() {
    return {
      prompt: '',
      negativePrompt: '低质量, 模糊, 畸形, 多余的肢体, 额外的手指',
      generatedImages: [],
      historyList: [],
      isLoading: false
    };
  },
  
  onLoad() {
    // 初始化RunningHub
    runningHubUtils.initRunningHub();
    
    // 从本地存储加载历史记录
    const history = uni.getStorageSync('aiImageHistory');
    if (history) {
      try {
        this.historyList = JSON.parse(history) || [];
      } catch (e) {
        this.historyList = [];
      }
    }
  },
  
  methods: {
    // 生成图像
    handleGenerateImage() {
      if (!this.prompt) {
        uni.showToast({
          title: '请输入正向提示词',
          icon: 'none'
        });
        return;
      }
      
      this.isLoading = true;
      
      runningHubUtils.generateImage({
        prompt: this.prompt,
        negativePrompt: this.negativePrompt,
        onSuccess: (imageResult) => {
          this.isLoading = false;
          this.generatedImages = imageResult;
          
          // 保存到历史记录
          this.saveToHistory(imageResult);
        },
        onError: (error) => {
          this.isLoading = false;
          uni.showToast({
            title: error.message || '生成失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 保存到历史记录
    saveToHistory(images) {
      const historyItem = {
        prompt: this.prompt,
        negativePrompt: this.negativePrompt,
        images: images,
        time: new Date().toLocaleString()
      };
      
      this.historyList.unshift(historyItem);
      
      // 限制历史记录数量
      if (this.historyList.length > 10) {
        this.historyList = this.historyList.slice(0, 10);
      }
      
      // 保存到本地存储
      uni.setStorageSync('aiImageHistory', JSON.stringify(this.historyList));
    },
    
    // 预览图片
    previewImage(url) {
      const urls = this.generatedImages.map(img => img.fileUrl);
      uni.previewImage({
        current: url,
        urls: urls.length > 0 ? urls : [url]
      });
    },
    
    // 保存图片到相册
    saveImage(url) {
      uni.showLoading({
        title: '保存中...'
      });
      
      // 下载图片
      uni.downloadFile({
        url: url,
        success: (res) => {
          if (res.statusCode === 200) {
            // 保存到相册
            uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: () => {
                uni.hideLoading();
                uni.showToast({
                  title: '保存成功',
                  icon: 'success'
                });
              },
              fail: () => {
                uni.hideLoading();
                uni.showToast({
                  title: '保存失败',
                  icon: 'none'
                });
              }
            });
          } else {
            uni.hideLoading();
            uni.showToast({
              title: '下载失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          uni.hideLoading();
          uni.showToast({
            title: '下载失败',
            icon: 'none'
          });
        }
      });
    }
  }
};
</script>

<style lang="scss">
.container {
  padding: 30rpx;
  
  .title {
    font-size: 36rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom: 40rpx;
  }
  
  .section {
    margin-bottom: 40rpx;
    background-color: #fff;
    border-radius: 12rpx;
    padding: 20rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
    
    .section-title {
      font-size: 30rpx;
      font-weight: bold;
      margin-bottom: 20rpx;
      border-bottom: 1px solid #eee;
      padding-bottom: 10rpx;
    }
    
    .form {
      display: flex;
      flex-direction: column;
      margin-bottom: 20rpx;
      
      .prompt-input {
        height: 160rpx;
        border: 1px solid #eee;
        border-radius: 8rpx;
        padding: 20rpx;
        margin-bottom: 20rpx;
        font-size: 28rpx;
      }
    }
    
    .loading {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 200rpx;
      
      text {
        color: #666;
        font-size: 28rpx;
      }
    }
    
    .image-list {
      max-height: 600rpx;
      
      .image-item {
        margin-bottom: 20rpx;
        border-radius: 8rpx;
        overflow: hidden;
        
        .result-image {
          width: 100%;
          height: 400rpx;
          display: block;
        }
        
        .image-info {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 10rpx;
          background-color: #f9f9f9;
          
          .image-index {
            color: #666;
            font-size: 24rpx;
          }
        }
      }
    }
    
    .history-list {
      max-height: 800rpx;
      
      .history-item {
        margin-bottom: 30rpx;
        padding-bottom: 20rpx;
        border-bottom: 1px solid #f0f0f0;
        
        .history-prompt {
          font-size: 28rpx;
          color: #333;
          margin-bottom: 10rpx;
        }
        
        .history-images {
          display: flex;
          flex-wrap: nowrap;
          overflow-x: auto;
          margin-bottom: 10rpx;
          
          .history-image {
            width: 200rpx;
            height: 200rpx;
            margin-right: 10rpx;
            border-radius: 8rpx;
            flex-shrink: 0;
          }
        }
        
        .history-time {
          font-size: 24rpx;
          color: #999;
          text-align: right;
        }
      }
    }
    
    .empty {
      text-align: center;
      color: #999;
      padding: 40rpx 0;
      font-size: 28rpx;
    }
  }
}
</style> 